import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Select, Tooltip, Button, Modal } from 'antd';
import { WeaLocaleProvider, WeaDialog, WeaSearchGroup } from 'ecCom';
import { RenderForm } from '../emailSetting/util';
import { ValidateForm } from '../../util';

const getLabel = WeaLocaleProvider.getLabel;
const { Option } = Select;

@inject('routing', 'emailContactStore')
@observer
class ContactTop extends Component {
  constructor(props) {
    super(props);
    this.wrapCls = `${props.wrapCls}-top`;
    this.state = {
      newVisible: false,
      title: '',
      isEdit: false,
    };
  }

  renderGropItem = data => (
    <Option
      ecId={`${(this && this.props && this.props.ecId) || ''}_Option@7bp9wc`}
      value={`${data.goutId}-${data.groupName}-${data.count}`}
    >
      <Tooltip
        ecId={`${(this && this.props && this.props.ecId) || ''}_Tooltip@sdz8lt`}
        title={`${data.groupName} (${data.count})`}
        placement="bottomLeft"
      >
        <div className={`${this.wrapCls}-selectname`}>
          <span>{data.groupName}</span>&nbsp;<span>{`(${data.count})`}</span>
        </div>
      </Tooltip>
    </Option>
  );

  renderLine = data => (
    <div className="wea-split-line">
      <div className="wea-sl-item wea-sl-line" />
      <div className="wea-sl-item wea-sl-wrap ">
        <div className="wea-sl-text">{data}</div>
      </div>
    </div>
  );

  editGroup = () => {
    const {
      emailContactStore: { getCondition, newGroupForm, curgroup },
    } = this.props;
    let curGroupName = (curgroup && curgroup.split(' ')[0]) || '';
    getCondition(() => {
      newGroupForm.updateFields({ groupName: { value: curGroupName } });
    });
    this.setState({
      title: getLabel(83149, '编辑分组'),
      newVisible: true,
      isEdit: true,
    });
  };

  creatGroup = () => {
    const {
      emailContactStore: { getCondition },
    } = this.props;
    getCondition();
    this.setState({ title: getLabel(30131, '新建分组'), newVisible: true });
  };

  onCancel = () => {
    const {
      emailContactStore: { newGroupForm },
    } = this.props;
    this.setState({ title: '', newVisible: false });
    newGroupForm.resetForm();
  };

  saveGroup = () => {
    const {
      emailContactStore: { newGroupForm, curgroupId, updateGroup },
    } = this.props;
    const { isEdit } = this.state;
    const formParams = newGroupForm.getFormParams();
    ValidateForm(newGroupForm, () => {
      let params = isEdit
        ? { operation: 'updateGroupName', groupId: curgroupId, ...formParams }
        : {
            operation: 'addOrThenMoveOrCopy',
            groupId: curgroupId,
            ...formParams,
          };
      updateGroup(params);
      this.onCancel();
    });
  };

  // 删除分组
  deleteGroup = () => {
    const {
      emailContactStore: { deleteGroup, curgroupId },
    } = this.props;
    Modal.confirm({
      title: getLabel(384343, '确定要删除分组吗？'),
      content: (
        <span>
          {getLabel('500265', '删除后，分组下所有人员将从此分组列表中移除')}
        </span>
      ),
      okText: getLabel(826, '确定'),
      onOk: () => {
        let params = { operation: 'deleteGroup', groupId: curgroupId };
        deleteGroup(params);
      },
    });
  };

  getForm = (form, fields) => {
    const { isFormInit } = form;
    let group = [];
    isFormInit &&
      fields &&
      fields.map((c) => {
        let items = [];
        c.items.map(field => items.push({ com: RenderForm(form, field) }));
        group.push(
          <WeaSearchGroup
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaSearchGroup@fulxak@${c.title}`}
            col={1}
            title={c.title}
            needTigger={true}
            showGroup={c.defaultshow}
            items={items}
          />,
        );
      });
    return group;
  };

  render() {
    const { emailContactStore } = this.props;
    const { newVisible, title } = this.state;
    const {
      topLoading,
      curgroup,
      selectChange,
      sysgroups,
      usergroups,
      curgroupId,
      newGroupForm,
      newGroupFields,
    } = emailContactStore;
    let curFlag = curgroupId != 0 && curgroupId != '-1';
    const buttons = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@9tnlf9@ContactToponsave`}
        type="primary"
        onClick={this.saveGroup}
      >
        {getLabel(30986, '保存')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@pvygy2@ContactonCancel`}
        onClick={this.onCancel}
      >
        {getLabel(201, '取消')}
      </Button>,
    ];
    // const showGroup = ( // if need the selected name's style, can use it,but has some problem,such as the title show will change as [object, object]
    //   <div className={`${this.wrapCls}-selectname selected`}>
    //     <span>{curgroup && curgroup.split(' ')[0]}</span>&nbsp;<span>{curgroup && curgroup.split(' ')[1]}</span>
    //   </div>
    // );
    return [
      <Select
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Select@nylebj@Contactonselect`}
        dropdownMatchSelectWidth={false}
        loading={topLoading}
        value={curgroup}
        onChange={value => selectChange(value, this.creatGroup)}
        className={`${this.wrapCls}-select`}
        dropdownClassName={`${this.wrapCls}-options`}
      >
        {toJS(sysgroups) &&
          toJS(sysgroups).map(sysgroup => this.renderGropItem(sysgroup))}
        <Option
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Option@ipwyao@Contactonoptionmy`}
          value="label"
          disabled
          style={{
            color: '#8a8a8a',
            padding: 0,
            width: '100%',
            cursor: 'default',
          }}
        >
          {this.renderLine(getLabel(384345, '我的分组'))}
        </Option>
        {toJS(usergroups) &&
          toJS(usergroups).map(usergroup => this.renderGropItem(usergroup))}
        <Option
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Option@w6bykq@Contactonoptionnew`}
          value="new"
          style={{
            background: '#e9e9e9',
            textAlign: 'center',
            padding: '8px 0',
            width: '100%',
          }}
        >
          <span className="icon-email-New-group" />
          &nbsp;&nbsp;&nbsp;{getLabel(30131, '新建分组')}
        </Option>
      </Select>,
      <span className={`${this.wrapCls}-ops`}>
        {curFlag && [
          <span className="icon-email-Pay" onClick={this.editGroup} />,
          <span className="icon-email-delete" onClick={this.deleteGroup} />,
        ]}
      </span>,
      <WeaDialog
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaDialog@t7jag7@ContactonnewGroup`}
        visible={newVisible}
        title={title}
        icon={'icon-coms-email'}
        iconBgcolor="#a0b0ba"
        className={`${this.prefixCls}-newGroup`}
        style={{ width: 580 }}
        buttons={buttons}
        onCancel={this.onCancel}
      >
        {this.getForm(newGroupForm, newGroupFields)}
      </WeaDialog>,
    ];
  }
}

export default ContactTop;
